package csvm_v2.components;

import javax.swing.JLabel;
import utils.PriceUtility;
import utils.Triplet;

/**
 * CoinDispenser bertugas mengembalikan koin kembalian kepada customer
 *
 * @author Muqtafi Akhmad
 */
public class CoinDispenser {

    /**
     * reference ke coin stock
     */
    private CoinContainer coinStock;

    /**
     * konstruktor dari CoinDispenser dengan reference ke coin stock dari
     * vending machine
     *
     * @param coinStock coin stock
     */
    public CoinDispenser(CoinContainer coinStock) {
        this.coinStock = coinStock;
    }

    /**
     * mengembalikan sejumlah koin kepada customer
     *
     * @param dimeCount jumlah dime
     * @param nickelCount jumlah nickel
     * @param quarterCount jumlah quarter
     */
    public void dispenseCoins(Integer dimeCount, Integer nickelCount, Integer quarterCount,JLabel label) {
        if(label== null){
            System.out.println("Mengeluarkan koin dime sejumlah " + dimeCount);
            System.out.println("Mengeluarkan koin nickel sejumlah " + nickelCount);
            System.out.println("Mengeluarkan koin quarter sejumlah " + quarterCount);
        }else{
            label.setText(PriceUtility.CoinToPrice(nickelCount, dimeCount, quarterCount)+" Dime : "+dimeCount+" Nicle : "+nickelCount + " Quarter : "+quarterCount);
        }
    }

    /**
     * mengembalikan uang kembalian kepada customer
     *
     * @param totalMoney jumlah total uang kembalian
     * @return apakah proses pengembalian koin berhasil
     */
    public boolean giveChange(Integer totalMoney, JLabel label) {
        Triplet<Integer, Integer, Integer> changes = PriceUtility.PriceToCoin(coinStock.getDimeCount(), coinStock.getNickelCount(), coinStock.getQuarterCount(), totalMoney);
        if (changes != null) {
            coinStock.setQuarterCount(coinStock.getQuarterCount() - changes.getFirst());
            coinStock.setDimeCount(coinStock.getDimeCount() - changes.getSecond());
            coinStock.setNickelCount(coinStock.getNickelCount() - changes.getThird());
            dispenseCoins(changes.getSecond(), changes.getThird(), changes.getFirst(),label);
            return true;
        }
        return false;
    }
}
